package net.vsame.url2sql.action.validator;

import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.nio.charset.Charset;
import java.util.LinkedHashMap;
import java.util.Map;

import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;

import net.vsame.url2sql.url.impl.ActionInterceptor;

public class ValidatorHelper {
	
	private static Invocable jsFunction = null;
	private static ScriptEngine engine = null;
	
	static {
		resetJsInvocable();
	}
	
	public static void loadResource(String resource){
		// Run InvScript.js
		Reader scriptReader = new InputStreamReader(ActionInterceptor.class.getResourceAsStream(resource), Charset.forName("utf-8"));
		try {
			engine.eval(scriptReader);
		}catch (Exception e) {
			throw new RuntimeException(e);
		} finally {
			try {
				scriptReader.close();
			} catch (IOException e) {
			}
		}
	}
	
	public static void resetJsInvocable() {
		ScriptEngineManager manager = new ScriptEngineManager();
		engine = manager.getEngineByName("JavaScript");
		loadResource("/validator.js");
		loadResource("/formValidatorRegex.js");
		if (engine instanceof Invocable) {
			jsFunction = (Invocable) engine;
		}else{
			throw new RuntimeException("not suppont!");
		}
	}
	
	public static void eval(String js) throws ScriptException{
		engine.eval(js);
	}

	/**
	 * @param map 数据map
	 * @param methodRoles 方法上的规则(注解)
	 * @param clazzRoles 类上的规则(注解)
	 * @return
	 */
	public static Map<String, String> v(Map<String, String[]> map, String array){
		Map<String, String> errors = new LinkedHashMap<String, String>();
		try {
			jsFunction.invokeFunction("init", map, errors, array);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
		return errors;
	}
	
	public static void main(String[] args) {
		Map<String, String[]> map = new LinkedHashMap<String, String[]>();
		map.put("mail", new String[]{"gaollg@sina.com!"});
		StringBuffer sb = new StringBuffer();
		sb.append("[");
		sb.append("{\"name\":\"pagesize\",\"info\":\"X\",\"focus\":\"D\",\"success\":\"S\",\"error\":\"页码必须为整数\",\"func\":\"v('+intege', $);\",\"option\":\"true\"}");
		sb.append(",");
		sb.append("{'name':'mail','info':'邮箱','focus':'获得焦点','success':'成功','error':'','func':'v(\"email\", $); return false', 'option':'true'}");
		sb.append("]");
		long begin = System.currentTimeMillis();
		Map<String, String> errors = ValidatorHelper.v(map, sb.toString());
		System.out.println(System.currentTimeMillis() - begin);
		System.out.println(errors);
	}
	
	
}